from flask import Flask, request
import hashlib

app = Flask(__name__)

# 自定义 Token，需与微信公众号后台配置一致
WECHAT_TOKEN = "9e2bc6641b1846a09097ff87ee4e"


@app.route('/wechat', methods=['GET'])
def wechat_verify():
    """
    微信服务号 Token 验证接口
    """
    # 获取请求参数
    signature = request.args.get('signature', '')
    timestamp = request.args.get('timestamp', '')
    nonce = request.args.get('nonce', '')
    echostr = request.args.get('echostr', '')

    # 校验参数是否完整
    if not all([signature, timestamp, nonce, echostr]):
        return "Invalid request", 400

    # 1. 将 token、timestamp、nonce 按字典序排序并拼接
    sorted_params = sorted([WECHAT_TOKEN, timestamp, nonce])
    concatenated_string = ''.join(sorted_params)

    # 2. 对拼接后的字符串进行 SHA-1 加密
    sha1 = hashlib.sha1()
    sha1.update(concatenated_string.encode('utf-8'))
    generated_signature = sha1.hexdigest()

    # 3. 比较生成的签名与微信提供的签名
    if generated_signature == signature:
        # 验证成功，返回 echostr
        return echostr
    else:
        # 验证失败
        return "Signature verification failed", 403


if __name__ == '__main__':
    # 启动 Flask 应用，监听所有地址（0.0.0.0）
    app.run(host='0.0.0.0', port=5000)
